﻿using ErrorOr;
using Gnivc.CarDealership.Api.Application.Abstractions.Repositories;
using Gnivc.CarDealership.Api.Application.Dtos;
using MediatR;

namespace Gnivc.CarDealership.Api.Application.Queries.Vehicles.GetAvailableVehicles;

public class GetAvailableVehiclesQueryHandler
    : IRequestHandler<GetAvailableVehiclesQuery, ErrorOr<GetAvailableVehiclesResult>>
{
    private readonly IVehicleRepository _vehicleRepository;

    public GetAvailableVehiclesQueryHandler(IVehicleRepository vehicleRepository)
    {
        _vehicleRepository = vehicleRepository;
    }

    public async Task<ErrorOr<GetAvailableVehiclesResult>> Handle(
        GetAvailableVehiclesQuery query, 
        CancellationToken cancellationToken)
    {
        var selectedDate = query.SelectedDate.ToUniversalTime();

        var getVehiclesResult = 
            await _vehicleRepository.GetAvailablesAsync(
                selectedDate, 
                query.BrandId, 
                query.ModelId);

        if (getVehiclesResult.IsError)
            return getVehiclesResult.Errors;

        return new GetAvailableVehiclesResult(getVehiclesResult.Value);
    }
}
